package com.csjy.migration.hnnd.business;

import com.csjy.migration.hnnd.DbUtil;
import com.csjy.migration.hnnd.DictTool;
import com.csjy.migration.hnnd.MD5Utils;
import com.csjy.migration.hnnd.ProgramArgument;
import com.csjy.migration.hnnd.annotation.BusinessDataConverter;
import com.csjy.migration.hnnd.dict.PersonsRelationshipType;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * 关联法人表（法人表）
     * BT_ITEM_ASSURE_SECURITY --> nd_related_legal_persons
 */
@BusinessDataConverter(
        insertSql = "INSERT INTO ND_RELATED_LEGAL_PERSONS(ID, CREATE_NAME, CREATE_BY, CREATE_DATE, UPDATE_NAME, UPDATE_BY, UPDATE_DATE, SYS_ORG_CODE, SYS_COMPANY_CODE, BPM_STATUS, ASSOCIATION_ID, LEGAL_PERSON_NAME, CERTIFICATE_TYPE, CERTIFICATE_NUMBER, RELATIONSHIP_TYPE, JOINT_GUARANTEE, LEGAL_REPRESENTATIVE, LEGAL_ID_NUMBER, LEGALPHONENUMBER, LEGALADDRESS) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        updateSql = "UPDATE ND_RELATED_LEGAL_PERSONS SET CREATE_NAME = ?, CREATE_BY = ?, CREATE_DATE = ?, UPDATE_NAME = ?, UPDATE_BY = ?, UPDATE_DATE = ?, SYS_ORG_CODE = ?, SYS_COMPANY_CODE = ?, BPM_STATUS = ?, ASSOCIATION_ID = ?, LEGAL_PERSON_NAME = ?, CERTIFICATE_TYPE = ?, CERTIFICATE_NUMBER = ?, RELATIONSHIP_TYPE = ?, JOINT_GUARANTEE = ?, LEGAL_REPRESENTATIVE = ?, LEGAL_ID_NUMBER = ?, LEGALPHONENUMBER = ?, LEGALADDRESS = ? WHERE ID = ?",
        findMigratedIdListSql = "SELECT T1.ID FROM ND_RELATED_LEGAL_PERSONS T1 LEFT JOIN ND_PROJECT_INFO T2 ON T1.ASSOCIATION_ID = T2.CUSTOMER_ID WHERE T2.ID = ? ",
        seq = 204
)
public class NdRelatedLegalPersons extends AbstractBusiness {

    public NdRelatedLegalPersons(DbUtil sourceDbUtil, DbUtil targetDbUtil, SourceBusinessData sourceData, ProgramArgument programArgument, String projectId) throws SQLException {
        super(sourceDbUtil, targetDbUtil, sourceData, programArgument, projectId);
    }

    @Override
    public void migrate() throws Exception {

        List<Map> btItemAssureSecurityList = this.sourceData.getBtItemAssureSecurityList();

        // btItemAssureSecurityList数据条件筛选 auditWorkflowNo IS NULL OR auditFlag = 2，并且是法人的数据
        List<Map> insertRowDatas = btItemAssureSecurityList.stream()
                .filter(row -> (
                        row.get("AUDITWORKFLOWNO") == null
                                || row.get("AUDITWORKFLOWNO") == ""
                                || "2".equals(row.get("AUDITFLAG").toString()))
                        && row.get("OWNERTYPE") != null
                        && row.get("BUSIREGISTCODE") != null
                        && "1".equals(row.get("OWNERTYPE").toString())
                ).collect(Collectors.toList());


        for (Map btItemAssureSecurity : insertRowDatas) {
            String id = buildId(btItemAssureSecurity);
            // 判断是否需要覆盖迁移
            int needMigratedResult = this.needMigrated(id);
            if(needMigratedResult == 0) {
                continue;
            }
            try {

                // 单条插入或更新
                if (needMigratedResult == 1) {
                    this.targetDbUtil.updateByParams(updateSql, this.buildValues(btItemAssureSecurity), true);
                    // 批量插入或更新 和 单条插入或更新 二选一
//                this.batchUpdateValues.add(this.buildValues(btItemAssureSecurity));
                } else {
                    this.targetDbUtil.updateByParams(insertSql, this.buildValues(btItemAssureSecurity));
                    // 批量插入或更新 和 单条插入或更新 二选一
//                this.batchInsertValues.add(this.buildValues(btItemAssureSecurity));
                }
            }catch(Exception e){
                if(e.getMessage().contains("C0033624") || e.getMessage().contains("违反唯一约束条件")){
                    continue;
                }
                throw e;
            }
        }

    }


    public String buildId(Map btItemAssureSecurity){
        // 基础表数据业务主键
        String ndCounterGuaranteeMeasuresOriginalId = this.sourceData.getBtItemBasic().get(0).get("ENTERPRISENO")
                + "-" + btItemAssureSecurity.get("BUSIREGISTCODE").toString();
        return MD5Utils.stringToMD5(ndCounterGuaranteeMeasuresOriginalId);
    }

    public List buildValues(Map btItemAssureSecurity){
        List values = new ArrayList();

        // todo

        //ID	主键
        values.add(buildId(btItemAssureSecurity));
        //CREATE_NAME	创建人名称
        values.add(null);
        //CREATE_BY	创建人登录名称
        values.add(btItemAssureSecurity.get("CREATE_TIME"));
        //CREATE_DATE	创建日期
        values.add(null);
        //UPDATE_NAME	更新人名称
        values.add(null);
        //UPDATE_BY	更新人登录名称
        values.add(null);
        //UPDATE_DATE	更新日期
        values.add(btItemAssureSecurity.get("MODIFY_TIME"));
        //SYS_ORG_CODE	所属部门
        values.add(null);
        //SYS_COMPANY_CODE	所属公司
        values.add("002");
        //BPM_STATUS	流程状态
        values.add("1");


        //ASSOCIATION_ID	关联ID nd_project_info.custom_id todo 需要确定旧系统取数规则
        values.add(this.sourceData.getBtItemBasic().get(0).get("ENTERPRISENO"));
        //LEGAL_PERSON_NAME	法人关联人名称
        values.add(btItemAssureSecurity.get("OWNERNAME"));
        //CERTIFICATE_TYPE	关联企业证件类型 新系统数据 1：统一社会信用代码 ，2-注册号
        values.add("1");
        //CERTIFICATE_NUMBER	关联企业证件号码
        values.add(btItemAssureSecurity.get("BUSIREGISTCODE"));
        //relationship_type	经营关系类型
        values.add(DictTool.getTargetDictCode(PersonsRelationshipType.class,btItemAssureSecurity.get("RELATIONTYPE")));
        //JOINT_GUARANTEE	是否连带保证 旧系统无此数据
        values.add(null);
        //LEGAL_REPRESENTATIVE	法定代表人
        values.add(btItemAssureSecurity.get("CORPORATION"));
        //LEGAL_ID_NUMBER	法定代表人身份证号码
        values.add(btItemAssureSecurity.get("CORPORATIONCODE"));
        //LEGALPHONENUMBER	法人手机号码
        values.add(btItemAssureSecurity.get("LINKTEL"));
        //LEGALADDRESS	法人通讯地址
        values.add(btItemAssureSecurity.get("OWNERADDRESS"));



        return values;
    }
}
